package com.hanhai.material.wages.controller;

import com.alibaba.fastjson.JSONObject;
import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultTool;
import com.hanhai.material.wages.entity.FinUserRoster;
import com.hanhai.material.wages.entity.SysAttendanceForm;
import com.hanhai.material.wages.service.FinUserRosterService;
import com.hanhai.material.wages.service.SysAttendanceFormService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import static com.hanhai.material.utils.TimeUtils.fromDateToString;
import static com.hanhai.material.wages.entity.table.FinUserRosterTableDef.FIN_USER_ROSTER;
import static com.hanhai.material.wages.entity.table.SysAttendanceFormTableDef.SYS_ATTENDANCE_FORM;

/**
 * 控制层。
 *
 * @author youchuang
 * @since 2023/10/25 17:34:51
 */
@RestController
@RequestMapping("/fin_user_roster")
@Log4j2
public class FinUserRosterController {

    @Autowired
    private FinUserRosterService finUserRosterService;

    /**
     * 添加。
     *
     * @param finUserRoster
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("save")
    public boolean save(@RequestBody FinUserRoster finUserRoster) {
        return finUserRosterService.save(finUserRoster);
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("remove/{id}")
    public boolean remove(@PathVariable Serializable id) {
        return finUserRosterService.removeById(id);
    }

    /**
     * 根据主键更新。
     *
     * @param finUserRoster
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("update")
    public boolean update(@RequestBody FinUserRoster finUserRoster) {
        return finUserRosterService.updateById(finUserRoster);
    }


    /**
     * 查询所有。
     *
     * @return 所有数据
     */
    @GetMapping("list")
    public List<FinUserRoster> list() {
        return finUserRosterService.list();
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("getInfo/{id}")
    public FinUserRoster getInfo(@PathVariable Serializable id) {
        return finUserRosterService.getById(id);
    }

    /**
     * 分页查询。
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public Page<FinUserRoster> page(Page<FinUserRoster> page) {
        return finUserRosterService.page(page);
    }

    @PostMapping("/getUserInfo/{jobNo}")
    public Result<?> getUserInfo(@PathVariable String jobNo) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(FIN_USER_ROSTER.JOB_NO.eq(jobNo));
        queryWrapper.orderBy(FIN_USER_ROSTER.ARCHIVES_DATE, false);
        queryWrapper.limit(1);
        FinUserRoster finUserRoster = this.finUserRosterService.getOne(queryWrapper);
        return finUserRoster == null ? ResultTool.fail() : ResultTool.success(finUserRoster);
    }

    @Autowired
    SysAttendanceFormService sysAttendanceFormService;

    @PostMapping("/getUserList/{isSign}")
    public Result<?> getUserListByDirectlyManager(@PathVariable boolean isSign, @RequestBody FinUserRoster finUserRoster) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(FIN_USER_ROSTER.DIRECTLY_MANAGE_ID.eq(finUserRoster.getUserId())).or(FIN_USER_ROSTER.DEPARTMENT_HEAD.eq(finUserRoster.getUserName()));
        queryWrapper.where(FIN_USER_ROSTER.ARCHIVES_DATE.eq(finUserRoster.getArchivesDate()));
        queryWrapper.orderBy(FIN_USER_ROSTER.JOB_NO, true);
        List<FinUserRoster> finUserRosterList = this.finUserRosterService.list(queryWrapper);

        if (isSign) {
            List<SysAttendanceForm> attendanceFormList = new ArrayList<>();
            System.out.println("开始点名");
            queryWrapper=QueryWrapper.create();
            queryWrapper.where(SYS_ATTENDANCE_FORM.WORK_DATE.eq(fromDateToString("yyyy-MM-dd",finUserRoster.getArchivesDate())));
            queryWrapper.where(SYS_ATTENDANCE_FORM.DIRECTLY_MANAGER_USER_ID.eq(finUserRoster.getUserId()));
            attendanceFormList=this.sysAttendanceFormService.list(queryWrapper);
            if(attendanceFormList.isEmpty()) {
                for (FinUserRoster userRoster : finUserRosterList) {
                    SysAttendanceForm attendanceForm = new SysAttendanceForm();
                    String id = fromDateToString("yyyyMMdd", finUserRoster.getArchivesDate()) + userRoster.getJobNo();
                    attendanceForm.setId(id);
                    attendanceForm.setWorkDate(finUserRoster.getArchivesDate());
                    attendanceForm.setUserId(userRoster.getUserId());
                    attendanceForm.setCreateUserId(finUserRoster.getUserId());
                    attendanceForm.setPosition(userRoster.getPosition());
                    attendanceForm.setIsNormal(true);
                    attendanceForm.setJobNo(userRoster.getJobNo());
                    attendanceForm.setUserName(userRoster.getUserName());
                    attendanceForm.setGroupName(userRoster.getGroupName());
                    attendanceForm.setDirectlyManager(userRoster.getDirectlyManage());
                    attendanceForm.setDirectlyManagerUserId(finUserRoster.getUserId());
                    attendanceForm.setDept(finUserRoster.getDeptLevel2());
                    attendanceForm.setSummary("正常出勤");
                    attendanceForm.setEnd(false);
                    SysAttendanceForm sysAttendanceForm = this.sysAttendanceFormService.getById(id);
                    if (sysAttendanceForm != null) {
                        this.sysAttendanceFormService.updateById(attendanceForm);
                    } else {
                        this.sysAttendanceFormService.save(attendanceForm);
                    }
                    attendanceFormList.add(attendanceForm);
                }
                return attendanceFormList.isEmpty() ? ResultTool.fail() : ResultTool.success(attendanceFormList);

            }else{
                return  ResultTool.success(attendanceFormList);
            }
        }
        return finUserRosterList.isEmpty() ? ResultTool.fail() : ResultTool.success(finUserRosterList);
    }

    @PostMapping("/managerList")
    public Result<?> getManagerList(@RequestBody FinUserRoster finUserRoster) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where((FIN_USER_ROSTER.POSITION.like("线长")).or(FIN_USER_ROSTER.GROUP_POSITION.like("线长")));
        queryWrapper.where(FIN_USER_ROSTER.ARCHIVES_DATE.eq(fromDateToString("yyyy-MM-dd", finUserRoster.getArchivesDate())));
        queryWrapper.where(FIN_USER_ROSTER.DEPT_LEVEL1.eq(finUserRoster.getDeptLevel1()));
        List<FinUserRoster> finUserRosterList = this.finUserRosterService.list(queryWrapper);
        System.out.println("SQL:" + queryWrapper.toSQL());
        log.error("FInUser:{}", finUserRoster.toString());
        return finUserRosterList.isEmpty() ? ResultTool.fail() : ResultTool.success(finUserRosterList);
    }

    @PostMapping("/list")
    public Result<?> getFinUserRosterList(@RequestBody FinUserRoster finUserRoster) {
        String workDate=fromDateToString("yyyy-MM-dd",finUserRoster.getArchivesDate());
//        QueryWrapper queryWrapper=QueryWrapper.create();
//        queryWrapper.select("Distinct dept_level1");
////        finUserRosterQueryWrapper.eq("dept_level1", workShop);
//        queryWrapper.where(FIN_USER_ROSTER.ARCHIVES_DATE.eq(workDate));
//        queryWrapper.where(FIN_USER_ROSTER.DEPT_LEVEL1.isNotNull());
//        List<FinUserRoster> finUserRosterList = this.finUserRosterService.list(queryWrapper);
//        List<Object> list = new ArrayList<>();
//        queryWrapper =QueryWrapper.create();
//        queryWrapper.select("Distinct group_position");
////        finUserRosterQueryWrapper.eq("dept_level1", workShop);
//        queryWrapper.where(FIN_USER_ROSTER.GROUP_POSITION.isNotNull());
//        queryWrapper.where(FIN_USER_ROSTER.ARCHIVES_DATE.eq(workDate));
//        List<FinUserRoster> finUserRosterList1 = this.finUserRosterService.list(queryWrapper);
//        List<Object> list1 = new ArrayList<>();
//        for (FinUserRoster finUserRoster1 : finUserRosterList1) {
//            Map<Object, Object> map1 = new HashMap<>();
//            map1.put("value", finUserRoster1.getGroupPosition());
//            map1.put("label", finUserRoster1.getGroupPosition());
//            queryWrapper =QueryWrapper.create();
//            queryWrapper.select("Distinct user_name");
////            finUserRosterQueryWrapper.eq("dept_level1", workShop);
//
//            queryWrapper.where(FIN_USER_ROSTER.GROUP_POSITION.eq(finUserRoster1.getGroupPosition()));
//            queryWrapper.where(FIN_USER_ROSTER.ARCHIVES_DATE.eq(workDate));
//            queryWrapper.where(FIN_USER_ROSTER.POSITION.isNotNull());
//            List<FinUserRoster> finUserRosterList2 = this.finUserRosterService.list(queryWrapper);
//            List<Object> list2 = new ArrayList<>();
//            for (FinUserRoster finUserRoster2 : finUserRosterList2) {
//                Map<Object, Object> map2 = new HashMap<>();
//                map2.put("label", finUserRoster2.getUserName());
//                map2.put("value", finUserRoster2.getUserName());
//                list2.add(map2);
//            }
//            map1.put("children", list2);
//            list1.add(map1);

//        }

// 批量查询优化
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.select("Distinct dept_level1");
        queryWrapper.where(FIN_USER_ROSTER.ARCHIVES_DATE.eq(workDate));
        queryWrapper.where(FIN_USER_ROSTER.DEPT_LEVEL1.isNotNull());
        List<FinUserRoster> finUserRosterList = this.finUserRosterService.list(queryWrapper);

// 批量查询 group_position
        Set<String> groupPositions = finUserRosterList.stream()
                .map(FinUserRoster::getGroupPosition)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

// 使用 IN 查询方式
        queryWrapper = QueryWrapper.create();
        queryWrapper.select("Distinct group_position");
        queryWrapper.where(FIN_USER_ROSTER.GROUP_POSITION.in(groupPositions));
        queryWrapper.where(FIN_USER_ROSTER.ARCHIVES_DATE.eq(workDate));
        queryWrapper.where(FIN_USER_ROSTER.GROUP_POSITION.isNotNull());
        List<FinUserRoster> finUserRosterList1 = this.finUserRosterService.list(queryWrapper);

// 冗余查询条件合并
        queryWrapper = QueryWrapper.create();
        queryWrapper.select("Distinct user_name");
        queryWrapper.where(FIN_USER_ROSTER.ARCHIVES_DATE.eq(workDate).and(FIN_USER_ROSTER.POSITION.isNotNull()));
// 不需要再设置 GROUP_POSITION 条件，已在外层循环中处理

// 减少数据传输
        List<Object> list = new ArrayList<>(finUserRosterList1.size());
        for (FinUserRoster finUserRoster1 : finUserRosterList1) {
            Map<Object, Object> map1 = new HashMap<>();
            map1.put("value", finUserRoster1.getGroupPosition());
            map1.put("label", finUserRoster1.getGroupPosition());

            // 构建 list2
            queryWrapper = QueryWrapper.create();
            queryWrapper.select("Distinct user_name");
            queryWrapper.where(FIN_USER_ROSTER.GROUP_POSITION.eq(finUserRoster1.getGroupPosition()));
            queryWrapper.where(FIN_USER_ROSTER.ARCHIVES_DATE.eq(workDate));
            queryWrapper.where(FIN_USER_ROSTER.POSITION.isNotNull());
            List<FinUserRoster> finUserRosterList2 = this.finUserRosterService.list(queryWrapper);
            List<Object> list2 = new ArrayList<>();
            for (FinUserRoster finUserRoster2 : finUserRosterList2) {
                Map<Object, Object> map2 = new HashMap<>();
                map2.put("label", finUserRoster2.getUserName());
                map2.put("value", finUserRoster2.getUserName());
                list2.add(map2);
            }
            map1.put("children", list2);
            list.add(map1);
        }

        return finUserRosterList.isEmpty() ? ResultTool.fail() : ResultTool.success(list);
    }


    @PostMapping("/getByCondition")
    public Result<?> getFinUserListByCondition(@RequestBody FinUserRoster finUserRoster) {
        log.error("Fin:{}", JSONObject.toJSONString(finUserRoster));
        log.error("Fin:{}", JSONObject.toJSONString(finUserRoster.getArchivesDate()));
        String workDate=fromDateToString("yyyy-MM-dd",finUserRoster.getArchivesDate());
        String start=workDate;
        String localDate=workDate;
        QueryWrapper finUserRosterQueryWrapper=QueryWrapper.create();
//        finUserRosterQueryWrapper.select("name")
        finUserRosterQueryWrapper.select("Distinct user_name,user_id,job_no,shift");
//        finUserRosterQueryWrapper.eq("line_manage", dataModel.getManager()).or().eq("directly_manage",dataModel.getManager()).or().eq("department_head",dataModel.getManager());
        finUserRosterQueryWrapper.
                where(FIN_USER_ROSTER.DIRECTLY_MANAGE.eq(finUserRoster.getUserName()).and(FIN_USER_ROSTER.ARCHIVES_DATE.between(start,localDate))
                        .or(FIN_USER_ROSTER.LINE_MANAGE.eq(finUserRoster.getUserName()).and(FIN_USER_ROSTER.ARCHIVES_DATE.between(start,localDate)))
                        .or(FIN_USER_ROSTER.DEPARTMENT_HEAD.eq(finUserRoster.getUserName()).and(FIN_USER_ROSTER.ARCHIVES_DATE.between(start,localDate)))
        );
        finUserRosterQueryWrapper.orderBy(FIN_USER_ROSTER.JOB_NO,true);
        List<FinUserRoster> finUserRosterList = this.finUserRosterService.list(finUserRosterQueryWrapper);
        return finUserRosterList.isEmpty() ? ResultTool.fail() : ResultTool.success(finUserRosterList);
    }
}
